package org.kaede.alimama.client;

import android.content.Context;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
* @author Kaede E-mail:yehan@51xianqu.net
* @version 创建时间：2015年10月16日 下午3:44:40
* 类说明
*/
public class NettyClient {
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();

	public  NettyClient(final Context context)
	{
		b.group(workerGroup);
		b.channel(NioSocketChannel.class);
		b.option(ChannelOption.SO_KEEPALIVE, true);
		b.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast("encoder",new StringEncoder());
				ch.pipeline().addLast("decoder",new StringDecoder());
				ch.pipeline().addLast("handler",new AlimamaClientHandler(context));
			}
		});
	}

	public Channel connect(String ip,int port)
	{
		// Start the client.
		try {
			ChannelFuture f = b.connect(ip, port).sync();
			return f.channel();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
